<template>
  <div>
    <!-- 档案综合查询 -->
    <el-card class="box-card" :body-style="{ padding: '10px 10px 2px 10px' }">
      <el-form :inline="true" :model="queryParam" class="demo-form-inline" size="large">
        <el-form-item label="档号/题名">
          <el-input v-model="queryParam.archiveNoOrName" placeholder="请输入档号或题名" clearable></el-input>
        </el-form-item>
        <el-form-item label="上架状态">
          <el-select v-model="queryParam.stageStatus" placeholder="请选择" clearable>
            <el-option v-for="item in [
              { value: 1, label: '已上架' },
              { value: 2, label: '已下架' },
            ]" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="在库状态">
          <el-select v-model="queryParam.storeStatus" placeholder="请选择" clearable>
            <el-option v-for="item in [
              { value: 1, label: '在库' },
              { value: 2, label: '离库' },
            ]" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">查询</el-button>
          <el-button @click="rest">重置</el-button>
          <el-button type="primary" @click="advancedQuery">高级查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-plus" @click="handleAdd">加入档案车</el-button>
          <el-button type="primary" icon="el-icon-upload2" @click="exportExcel">导出</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card class="box-card" :body-style="{ padding: 10 }">
      <!-- <SortableTable v-if="tableProps.length > 0" :table-props="tableProps" @update="UpdateTable">
      </SortableTable> -->
      <el-table ref="multipleTable" :data="tableData" border style="width: 100%; overflow-y: auto" height="50vh"
        row-key="labelId" @selection-change="selectionChange">
        <el-table-column type="selection" width="55" align="center" sortable :reserve-selection="true">
        </el-table-column>
        <el-table-column v-for="item of tableProps" :key="item.props" :prop="item.prop" :label="item.title"
          :width="item.width" :sortable="item.sortable" :show-overflow-tooltip="item.showOverflowTooltip">
          <template #default="scope">
            <span v-if="item.prop === 'boxNo'">
              <el-link v-if="scope.row.boxNo" type="primary" :underline="false" style="font-size: 12px"
                @click="archivesByBoxNo(scope.row)">
                {{ scope.row[item.prop] }}
              </el-link>
              <span v-else>无</span>
            </span>
            <span v-else-if="item.prop === 'stageStatus'">
              <el-tag v-if="scope.row.stageStatus == 0">未上架</el-tag>
              <el-tag v-if="scope.row.stageStatus == 1" type="success">已上架</el-tag>
              <el-tag v-if="scope.row.stageStatus == 2" type="danger">已下架</el-tag>
            </span>
            <span v-else-if="item.prop === 'storeStatus'">
              <el-tag :type="statusInfo(scope.row).type">
                {{ statusInfo(scope.row).text }}
              </el-tag>
            </span>
            <span v-else-if="item.prop === 'positionId'">
              {{ scope.row.positionId_dictText }}
            </span>
            <span v-else>
              <span v-if="dictProps.map((dict) => dict.fieldName).includes(item.prop)">
                {{ getDictItemValue(item.prop, scope.row[item.prop]) }}
              </span>
              <span v-else>{{ scope.row[item.prop] }}</span>
            </span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="">
          <template #default="{ row }">
            <el-button link size="small" @click="handleLife(row)">生命周期</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-card class="box-card" :body-style="{ padding: 10 }">
      <pagination ref="pagination" :totalCount="totalCount" @pagination="pagination"></pagination>
    </el-card>
    <archives-by-box-no ref="archivesByBoxNo"></archives-by-box-no>
    <label-life-drawer ref="labelLifeDrawer"></label-life-drawer>
    <search-content ref="searchContent" @doSearch="doSearch"></search-content>
  </div>
</template>

<script>
import { archivePage, archiveExportExcel } from '@/api/rfid/label'
import { rfidAccountFieldDefinelistArchive } from '@/api/sys/field'
import { resetDefaultArchiveFieldSort } from '@/api/sys/field'

import { add } from '@/api/rfid/labelCar'
import { getDictItemsByCodes } from '@/api/sys/dict'
import archivesByBoxNo from '../rfid/dialog/archivesByBoxNo.vue'
import labelLifeDrawer from './drawer/labelLifeDrawer.vue'

export default {
  name: 'archivesQuery',
  components: { archivesByBoxNo, labelLifeDrawer },
  data() {
    return {
      totalCount: 0, //总数
      //查询条件
      searchModel: {
        pageNo: 1,
        pageSize: 10,
      },
      queryParam: {},
      tableData: [],
      tableProps: [],
      dictProps: [],
      dictItems: {},
      selectionData: [],
    }
  },
  created() {
    this.getArchiveFields()
  },
  methods: {
    statusInfo(row) {
      if (row.storeStatus === 0) return { type: '', text: '未入库' }
      if (row.storeStatus === 1) {
        return row.stageStatus === 1
          ? { type: 'success', text: '在库' }
          : { type: 'warning', text: '暂存' }
      }
      if (row.storeStatus === 2) return { type: 'danger', text: '离库' }
      return { type: '', text: '' }
    },
    toCamelCase(str) {
      // 首先将字符串分割成单词数组
      const words = str.split(/[-_\s]+/)

      // 如果字符串为空，返回空字符串
      if (words.length === 0) {
        return ''
      }

      // 将第一个单词小写，其余单词首字母大写，然后连接它们
      return (
        words[0].toLowerCase() +
        words
          .slice(1)
          .map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
          .join('')
      )
    },
    getArchiveFields() {
      rfidAccountFieldDefinelistArchive()
        .then((res) => {
          if (res.data.code === 200) {
            this.tableProps = res.data.data.map((item) => {
              return {
                ...item,
                title: item.fieldTitle,
                prop: this.toCamelCase(item.fieldName),
                width: '',
                checked: true,
                showOverflowTooltip: true,
              }
            })
            // 将res.data.data中dictCode不为null的提取出来，生成一个对象数组，对象中包含fieldName和dictCode
            this.dictProps = res.data.data
              .filter((item) => item.dictCode !== null && item.dictCode !== '')
              .map((item) => {
                return {
                  fieldName: this.toCamelCase(item.fieldName),
                  dictCode: item.dictCode,
                }
              })
            if (this.dictProps.length > 0) {
              const dictCodes = this.dictProps.map((item) => item.dictCode)
              this.getDictItems(dictCodes)
            }
            this.loadData()
          } else {
            this.$message.error(res.data.message)
          }
        })
        .catch((err) => {
          this.$message.error(err)
        })
    },
    // 根据字典编码数组获取字典值
    getDictItems(dictCodes) {
      getDictItemsByCodes(dictCodes)
        .then((res) => {
          if (res.data.code === 200) {
            this.dictItems = res.data.data
          } else {
            this.$message.error(res.data.message)
          }
        })
        .catch((err) => {
          this.$message.error(err)
        })
    },
    getDictItemValue(fieldName, value) {
      // 在dictProps中获取对象
      const dictItem = this.dictProps.find((item) => item.fieldName === fieldName)
      // 查询dictItem.dictCode对应的字典值
      return this.dictItems[dictItem.dictCode]?.find((item) => item.value === value)?.label
    },
    onSubmit() {
      this.$refs.pagination.resetPagination()

    },
    rest() {
      this.queryParam = {}
      this.$refs.pagination.resetPagination()
      this.$refs.searchContent.clearSearch()
    },
    advancedQuery() {
      this.$refs.searchContent.advancedQuery('archive')
    },
    doSearch(conditionJson) {
      this.queryParam.conditionJson = conditionJson
      this.loadData()
    },
    loadData() {
      var param = Object.assign(this.queryParam, this.searchModel)
      archivePage(param)
        .then((res) => {
          if (res.data.code === 200) {
            this.tableData = res.data.data.records
            this.totalCount = res.data.data.total
          } else {
            this.$message.error(res.data.message)
          }
        })
        .catch((err) => {
          this.$message.error(err)
        })
    },
    pagination(val) {
      this.searchModel.pageNo = val.page
      this.searchModel.pageSize = val.limit
      this.loadData()
    },
    async UpdateTable(tableProps) {
      const AfterTable = tableProps.map((item, index) => {
        return {
          defineId: item.defineId,
          title: item.title,
          fieldSort: index,
        }
      })
      const { data } = await resetDefaultArchiveFieldSort(AfterTable)
      if (data.code == 200) {
        this.tableProps = this.onUpdateTable(tableProps)
      } else {
        this.$message.error(data.message)
      }

    },
    selectionChange(val) {
      this.selectionData = val
    },
    handleAdd() {
      if (this.selectionData.length === 0) {
        this.$message.warning('请选择档案')
        return
      }
      var param = {
        labelIds: this.selectionData.map((item) => item.labelId),
      }
      add(param)
        .then((res) => {
          if (res.data.code === 200) {
            this.$message.success('加入档案车成功')
            this.$refs.multipleTable.clearSelection()
          } else {
            this.$message.warning(res.data.message)
          }
        })
        .catch((err) => {
          this.$message.error(err)
        })
    },
    archivesByBoxNo(row) {
      this.$refs.archivesByBoxNo.init(row)
    },
    exportExcel() {
      archiveExportExcel(this.queryParam)
        .then((res) => {
          // 创建一个新的URL代表指定的File对象或Blob对象
          const url = window.URL.createObjectURL(new Blob([res.data]))
          // 创建一个a标签用于下载
          const link = document.createElement('a')
          link.href = url
          link.setAttribute('download', '档案信息.xlsx') // 下载文件名
          document.body.appendChild(link)
          link.click()
        })
        .catch((err) => {
          this.$message.error(err)
        })
    },
    handleLife(row) {
      this.$refs.labelLifeDrawer.init(row)
    },
  },
}
</script>

<style scoped lang="less"></style>
